
#include "stdio.h"
#include "stdlib.h"
#include "gd32f1x0.h"
#include "systick.h"
#include "buffer.h"
#include "timer.h"
#include "fmc.h"
#include "rs485.h"
#include "usart.h"
#include "CRC16.h"

extern Controller_struct Controller;

extern RS485reveive_Buffer RS485BufferStruct;
extern UsartReceive_union RS485RecieveCmd;
extern PlatformReveive_Buffer PlatformBuffer;



void vbufferMessageProcessing(void){
	if(RS485BufferStruct.status){
		vbuffer485MessageProcessing();
		RS485BufferStruct.status=FALSE;
	}
	if(PlatformBuffer.status){
		vbufferPlatformMessageProcessing();
		PlatformBuffer.status=FALSE;
	}
}

void vbuffer485MessageProcessing(void){
	vbuffer485MessageFormat();
	vbuffer485InstructionParsing();
}

void vbuffer485MessageFormat(void){
	uint8_t RS485DataPos=0,TEMPDataPos=0;
	for(uint8_t i=0;i<rRS485reveive_Buffer_Len;i++){
		if(RS485BufferStruct.data[i]==0xFB){
			TEMPDataPos=i;
			
			for(;TEMPDataPos<(TEMPDataPos+RS485ParLenPositon+2);TEMPDataPos++){
				RS485RecieveCmd.DataByte[RS485DataPos++]=RS485BufferStruct.data[TEMPDataPos];
				if(TEMPDataPos>=rRS485reveive_Buffer_Len){TEMPDataPos=0;}
			}

			for(uint8_t i=0;(i<((RS485RecieveCmd.DataByte[RS485ParLenPositon]<<8)+RS485RecieveCmd.DataByte[RS485ParLenPositon+1])&&(i<RS485DataLen));i++){
				RS485RecieveCmd.DataByte[RS485DataPos++]=RS485BufferStruct.data[TEMPDataPos++];
				if(TEMPDataPos>=rRS485reveive_Buffer_Len){TEMPDataPos=0;}
			}
			
			RS485DataPos=RS485DataLen+23;
			
			for(;RS485DataPos<RS485DataLen+26;RS485DataPos++){
				RS485RecieveCmd.DataByte[RS485DataPos]=RS485BufferStruct.data[TEMPDataPos++];
				if(TEMPDataPos>=rRS485reveive_Buffer_Len){TEMPDataPos=0;}
			}
			
			break;
		}
	}

}

void vbuffer485InstructionParsing(void){
	
	if(RS485RecieveCmd.data.tdevid[0]==Controller.Controller.Info.DevID.DevID.area){
		
		if(RS485RecieveCmd.data.tdevid[1]==Controller.Controller.Info.DevID.DevID.type){
			
			if(
					(RS485RecieveCmd.data.tdevid[2]==Controller.Controller.Info.DevID.DevID.add[0])&&\
					(RS485RecieveCmd.data.tdevid[3]==Controller.Controller.Info.DevID.DevID.add[1])&&\
					(RS485RecieveCmd.data.tdevid[4]==Controller.Controller.Info.DevID.DevID.add[2])&&\
					(RS485RecieveCmd.data.tdevid[5]==Controller.Controller.Info.DevID.DevID.add[3])&&\
					(RS485RecieveCmd.data.tdevid[6]==Controller.Controller.Info.DevID.DevID.add[4])&&\
					(RS485RecieveCmd.data.tdevid[7]==Controller.Controller.Info.DevID.DevID.add[5])
			
				)
			{
					unsigned int crccalc=uiCRC16Calc(&RS485RecieveCmd.DataByte[1],(22+(RS485RecieveCmd.data.parlen[0]<<8)+RS485RecieveCmd.data.parlen[1]));
					
					if(crccalc==(RS485RecieveCmd.data.crc[0]<<8)+RS485RecieveCmd.data.crc[1]){
						
						switch(RS485RecieveCmd.data.cmd[0]){
							
						}
						
					}
				
			}
			
		}
		
		
		
	}
	

	
}


void vbufferPlatformMessageProcessing(void){
	
}

